package ui.task;

import cerebrum.common.CommonConst;
import cerebrum.common.ConfigPropertiesUtil;
import cerebrum.cache.ImagesDataLoaderCache;
import cerebrum.cache.RunTimeContextCache;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import ui.panel.showroom.WallpaperStage;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 壁纸刷新task
 */
public class WallpaperMotionTask extends Thread {

    //获取刷新频率
    private Long frequency = Long.valueOf(ConfigPropertiesUtil.get("frequency"));

    public WallpaperMotionTask() {

    }

    public WallpaperMotionTask(WallpaperStage stage) {

    }

    @Override
    public void run() {
        dispatcher();
    }

    //定时任务
    private void dispatcher() {

        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                change();

                if (Boolean.FALSE.equals(ImagesDataLoaderCache.getTaskStatus()) ||Boolean.FALSE.equals(RunTimeContextCache.getThreadStatus())) {
                    timer.cancel();// 停止定时器
                }
            }
        };
        timer.schedule(task, 0, frequency);// 立即执行一次，后面每隔3秒执行一次
    }

    private void change() {
        Platform.runLater(() -> {
            WallpaperStage wallpaperStage = WallpaperStage.getInstance();
            //缩放图片到指定尺寸
            ImageView image = (ImageView) wallpaperStage.$("WallpaperStage-image");
            image.setFitWidth(CommonConst.SYSTEMWIDTH);
            image.setFitHeight(CommonConst.SYSTEMHEIGHT);
            Image image1 = new Image(ImagesDataLoaderCache.next());
            image.setImage(image1);
        });

    }

}
